package com.lengyu.vxminiprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lengyu.vxminiprogram.convert.IUserConverter;
import com.lengyu.vxminiprogram.dto.UserDto;
import com.lengyu.vxminiprogram.entity.User;
import com.lengyu.vxminiprogram.mapper.UserMapper;
import com.lengyu.vxminiprogram.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyu
 * @since 2023-01-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private IUserConverter userConverter;

    @Override
    public String getUserNameById(String id) {
        UserDto userDto = getUserDtoById(id);
        if(userDto == null){
            return StringUtils.EMPTY;
        }
        else{
            return userDto.getUsername();
        }

    }

    @Override
    public String getUserIdByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",name);
        User user = getOne(queryWrapper,false);
        if(user == null){
            return null;
        }
        else{
            return user.getId();
        }
    }

    @Override
    /**
     * Cacheable：触发缓存填充的操作，检查缓存是否存在，存在则取缓存数据,直接返回，不存在则查数据库写入缓存
     * value：缓存的名称，每个缓存名称下可以有多个key
     * key：缓存的key
     * condition：设置缓存的判断条件，当返回值不为 null 时才存缓存
     * unless：与condition相反，满足条件则不缓存
     * @param id
     * @return
     */
    @Cacheable(value = "userCache", key = "#userId", unless = "#result == null")
    public UserDto getUserDtoById(String userId) {
        System.out.println("没走缓存");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",userId);
        queryWrapper.select("id","username","sex","birthday","email","delete_flag");
        User user = getOne(queryWrapper,false);
        if(user == null){
            return new UserDto();
        }
        else{
            UserDto userDto = userConverter.entityToDto(user);
            return userDto;
        }
    }
}
